package com.hbnu.utils;

import com.alibaba.fastjson.JSON;
import com.hbnu.pojo.WeChatLoginResponse;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Base64;

/**
 * 微信工具类
 */
public class WeChatUtil {

    private static final String CODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";

    static {
        // 添加BouncyCastle提供者
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 调用微信code2Session接口
     */
    public static WeChatLoginResponse code2Session(String appId, String secret, String jsCode) {
        System.out.println("[WeChatUtil] 开始调用微信code2Session接口");
        System.out.println("[WeChatUtil] AppID: " + appId);
        System.out.println("[WeChatUtil] Secret: " + (secret != null ? secret.substring(0, Math.min(8, secret.length())) + "..." : "null"));
        System.out.println("[WeChatUtil] JsCode: " + (jsCode != null ? jsCode.substring(0, Math.min(10, jsCode.length())) + "..." : "null"));

        // 如果是测试环境或者使用默认配置，返回模拟数据
        if ("your_wechat_app_id".equals(appId) || "your_app_id".equals(appId) || jsCode.startsWith("test_")) {
            System.out.println("[WeChatUtil] 检测到测试环境，返回模拟数据");
            WeChatLoginResponse mockResponse = new WeChatLoginResponse();
            mockResponse.setOpenid("mock_openid_" + System.currentTimeMillis());
            mockResponse.setSessionKey("mock_session_key_" + System.currentTimeMillis());
            // unionid字段已移除，不再设置mock数据
            System.out.println("[WeChatUtil] 模拟响应: " + JSON.toJSONString(mockResponse));
            return mockResponse;
        }

        String url = String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                CODE2SESSION_URL, appId, secret, jsCode);
        System.out.println("[WeChatUtil] 请求URL: " + url.replaceAll("secret=[^&]*", "secret=***"));

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);

            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("[WeChatUtil] HTTP状态码: " + statusCode);

                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                    System.out.println("[WeChatUtil] 微信API原始响应: " + result);

                    WeChatLoginResponse weChatResponse = JSON.parseObject(result, WeChatLoginResponse.class);
                    System.out.println("[WeChatUtil] 解析后的响应对象: " + JSON.toJSONString(weChatResponse));
                    System.out.println("[WeChatUtil] 响应是否成功: " + weChatResponse.isSuccess());

                    if (!weChatResponse.isSuccess()) {
                        System.err.println("[WeChatUtil] 微信API返回错误 - errcode: " + weChatResponse.getErrcode() + ", errmsg: " + weChatResponse.getErrmsg());
                    }

                    return weChatResponse;
                } else {
                    System.err.println("[WeChatUtil] HTTP响应实体为空");
                }
            }
        } catch (Exception e) {
            System.err.println("[WeChatUtil] 网络请求异常: " + e.getClass().getSimpleName() + " - " + e.getMessage());
            e.printStackTrace();
            WeChatLoginResponse errorResponse = new WeChatLoginResponse();
            errorResponse.setErrcode(-1);
            errorResponse.setErrmsg("网络请求失败: " + e.getMessage());
            return errorResponse;
        }

        System.err.println("[WeChatUtil] 未知错误，请求失败");
        WeChatLoginResponse errorResponse = new WeChatLoginResponse();
        errorResponse.setErrcode(-1);
        errorResponse.setErrmsg("请求失败");
        return errorResponse;
    }

    /**
     * AES解密微信加密数据
     */
    public static String decryptData(String encryptedData, String sessionKey, String iv) {
        try {
            byte[] dataByte = Base64.getDecoder().decode(encryptedData);
            byte[] keyByte = Base64.getDecoder().decode(sessionKey);
            byte[] ivByte = Base64.getDecoder().decode(iv);

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(ivByte);

            cipher.init(Cipher.DECRYPT_MODE, spec, ivSpec);
            byte[] resultByte = cipher.doFinal(dataByte);

            return new String(resultByte, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}